package com.xiumu.controller.sys;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiumu.common.core.exception.base.SysException;
import com.xiumu.common.core.page.PageQuery;
import com.xiumu.common.core.result.ResultJSON;
import com.xiumu.common.core.utils.AssertUtil;
import com.xiumu.config.XiuMuProperties;
import com.xiumu.pojo.sys.entity.HaloFile;
import com.xiumu.pojo.sys.query.HaloFileQuery;
import com.xiumu.service.sys.HaloFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件服务接口
 *
 * @Author XiuMu
 * @Date 2023/1/29 11:17
 **/
@Slf4j
@RestController
public class HaloFileController {

    @Autowired
    private HaloFileService haloFileService;

    @Autowired
    private XiuMuProperties properties;

    /**
     * 分页查询
     * 可传递查询参数，按照某些字段分页查询
     *
     * @param pageQuery 分页条件，查询参数
     * @return
     */
    @PostMapping("/page/file")
    public ResultJSON<Page<HaloFile>> page(@RequestBody PageQuery<HaloFileQuery, HaloFile> pageQuery) {
        return ResultJSON.querySuccess(haloFileService.listPage(pageQuery));
    }

    /**
     * 文件上传
     *
     * @param file 文件
     * @return
     */
    @PostMapping("/file")
    public ResultJSON<String> uploadFile(@RequestParam("file") MultipartFile file) {
        AssertUtil.isFalse(file.isEmpty(), SysException.FILE_EMPTY);
        // 判断文件格式是否允许上传
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        AssertUtil.isTrue(StrUtil.isNotBlank(suffix) && properties.getAllowedUploadFileType().contains(suffix.toLowerCase()), SysException.FILE_TYPE_NOT_ALLOWED);
        return ResultJSON.createSuccess(haloFileService.uploadFile(file)).setMsg("上传成功！");
    }

    /**
     * 文件删除
     * @param fileKey 文件的key
     * @return
     */
    @DeleteMapping("/file/{fileKey}")
    public ResultJSON<Boolean> deleteFile(@PathVariable("fileKey") String fileKey) {
        return ResultJSON.deleteSuccess(haloFileService.deleteByFileKey(fileKey));
    }
}
